import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:developer';

import 'package:kasax_demos2/day14_stream/data_bloc.dart';

/// StreamBuilder 数据发生变化，会自动构建小部件
class StreamBuilderDemo2Home extends StatefulWidget {
  const StreamBuilderDemo2Home({Key? key}) : super(key: key);

  @override
  _StreamBuilderDemo2HomeState createState() => _StreamBuilderDemo2HomeState();
}

class _StreamBuilderDemo2HomeState extends State<StreamBuilderDemo2Home> {
  List<String> _list = [];
  DataBloc _dataBloc = DataBloc();

  @override
  void initState() {
    super.initState();

    _dataBloc.init((s) {
      setState(() {
        _list.clear();
        _list = s;
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    _dataBloc.close();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("broadcast 多次订阅-2"),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: _addData2Stream,
      ),
      body: Container(
        margin: EdgeInsets.only(left: 15, right: 15),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            SizedBox(
              height: 15,
            ),
            Expanded(
                child: Container(
              child: SingleChildScrollView(
                child: Container(
                  child: Text(
                    "流数据: $_list",
                    style: Theme.of(context).textTheme.body1,
                  ),
                ),
              ),
            )),
            SizedBox(
              height: 15,
            ),
          ],
        ),
      ),
    );
  }

  _addData2Stream() {
    _dataBloc.add("test");
  }
}
